package com.taskScheduler.pool;

import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.taskScheduler.task.PoolTask;
import com.taskScheduler.task.TimingTaskInfo;

public class TimingTaskPool {
	/**
	 * ThreadPoolExecutors to manage the transfer of the timingTask
	 */
	private ScheduledExecutorService executor;
	public TimingTaskPool(int poolSize){
		executor=(ScheduledExecutorService)Executors.newScheduledThreadPool(poolSize);
	}
	/*Now we will use ConcurrentLinkedQueue, in the future we may use Queue and do the synchronied work ourselves.*/
	//(taskInfoQueue,runnableTaskQueue)
	public void excuteTasks(ConcurrentLinkedQueue<TimingTaskInfo> queue,BlockingQueue<Runnable> runnableTaskqueue){
		while(!queue.isEmpty()){
			TimingTaskInfo timingTaskInfo =queue.poll();
			PoolTask poolTask=new PoolTask(timingTaskInfo,runnableTaskqueue);
			Date excutedTime=timingTaskInfo.getExcutedTime();
			long delay_s=(excutedTime.getTime()-System.currentTimeMillis())/1000;
			executor.schedule(poolTask,delay_s,TimeUnit.SECONDS);
		}
	}
	
	/**
	 * This method shuts down the executor
	 */
	public void endServer() {
		executor.shutdown();
	}
}
